package com.haiqiu.busines.controller;

import com.haiqiu.syslog.annotation.Limit;
import com.haiqiu.busines.entity.SysFile;
import com.haiqiu.busines.service.SysFileService;
import com.haiqiu.common.controller.BaseController;
import com.haiqiu.common.exception.BaseException;
import com.haiqiu.common.page.PageRequest;
import com.haiqiu.common.result.Constants;
import com.haiqiu.common.result.ResultData;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.Set;

/**
 * @author haiqiu
 * ftp文件管理
 */
@Tag(name = "文件管理", description = "文件上传下载等方法")
@RestController
@RequestMapping("/file")
public class FileController extends BaseController {
    @Autowired
    private SysFileService sysFileService;

    @Value("${http.parent:C:\\}")
    private String parent;


    @Operation(summary = "系统背景图logo文件上传")
    @PostMapping(value = "/theme/upload", consumes = "multipart/*")
    public ResultData uploadTheme(@Parameter(description = "请选择文件上传") MultipartFile file) {
        return decide((Object) sysFileService.uploadTheme(file));
    }


    @Parameters({
            @Parameter(description = "文件集合，支持多个", name = "files"),
            @Parameter(description = "上传文件存储方式：oss,ftp,server,qiniu,ftp"),
            @Parameter(description = "上传文件所属的文件夹", name = "folder"),
    })
    @Operation(summary = "批量文件文件上传")
    @PostMapping(value = "/upload", consumes = "multipart/*")
    public ResultData upload( MultipartFile file, String mode, String folder) {
        if (StringUtils.isEmpty(mode)){
            throw new BaseException("请选择上传模式");
        }
        if (!(mode.equals(Constants.OSS) || mode.equals(Constants.FTP)
                || mode.equals(Constants.SERVER) || mode.equals(Constants.QINIU))) {
            throw new BaseException("上传类型错误");
        }
        return decide((Object) sysFileService.upload(file, mode, folder));
    }


    @Limit(name = "下载文件请求",perSecond = 1)
    @Operation(summary = "服务器下载文件")
    @GetMapping(value = "/server/download")
    public ResultData serverDownload(@RequestParam String filePath) {
        sysFileService.downloadFile(filePath);
        return decide("文件已下载");
    }

    @Operation(summary = "服务器文件或文件夹重命名或移动文件")
    @GetMapping(value = "/server/rename")
    public ResultData serverRename(@Parameter(description = "源文件路径") @RequestParam String filePath,
                                   @Parameter(description = "重命名新名称或移动的文件或文件夹名称") @RequestParam String newName,
                                   @Parameter(description = "父级路径（可以是需要移动的路径）") @RequestParam String parentPath) {
        sysFileService.serverRename(filePath,newName,parentPath);
        return decide(Constants.SUCCESS);
    }

    @Operation(summary = "服务器复制文件或文件夹")
    @GetMapping(value = "/server/copy")
    public ResultData serverCopy(@Parameter(description = "源文件路径") @RequestParam String filePath,
                                   @Parameter(description = "重命名新名称或复制的文件或文件夹名称") @RequestParam String newName,
                                   @Parameter(description = "父级路径（可以是需要复制的路径）") @RequestParam String parentPath) {
        sysFileService.serverCopy(filePath,newName,parentPath);
        return decide(Constants.SUCCESS_COPY);
    }

    @Operation(summary = "ftp文件列表")
    @GetMapping(value = "/ftp/list")
    public ResultData show(@RequestParam(required = false) String folder) {
        return decide(sysFileService.show(folder));
    }

    @Operation(summary = "服务器文件列表")
    @Parameters({
            @Parameter(name = "folder",description = "文件父级路径"),
            @Parameter(name = "name",description = "文件或者文件夹搜索名称"),
            @Parameter(name = "sort",description = "排序方式：dateAsc时间正序排，dateDesc时间倒序排，" +
                    "SizeAsc大小正序排，sizeDesc大小倒序排"),
    })
    @GetMapping(value = "/server/list")
    public ResultData serverFileList(@RequestParam(required = false) String folder,
                                     @RequestParam(required = false) String name,
                                     @RequestParam(required = false) String sort) {
        return decide(sysFileService.serverFileList(folder,name,sort));
    }

    @Operation(summary = "获取当前目录的上一级目录")
    @GetMapping(value = "/server/back")
    public ResultData serverFileListBack(@RequestParam String folder) {
        if (StringUtils.isEmpty(folder)){
            throw new BaseException("获取目录为空");
        }
        if (parent.equals(folder)){
            return decide("已经在首页");
        }
        File file = new File(folder);
        return decide((Object) file.getParent());
    }

    @Operation(summary = "批量删除服务器文件或文件夹")
    @DeleteMapping("/server/delete")
    public ResultData deleteFiles(@RequestBody Set<String> filePaths) {
        return decide(String.format("成功删除%d条数据", sysFileService.deleteFiles(filePaths)));
    }

    @Operation(summary = "创建文件夹")
    @PostMapping("/server/folder")
    public ResultData addFolder(@RequestParam String folders) {
        sysFileService.addFolder(folders);
        return decide("创建成功");
    }

    @Operation(summary = "新增文件", description = "新增文件的操作")
    @PostMapping("")
    public ResultData insert(@Parameter(description = "新增文件，无须传ID") @RequestBody SysFile sysFile) {
        sysFileService.insert(sysFile);
        return decide(Constants.SUCCESS_ADD);
    }


    @Operation(summary = "修改文件", description = "修改文件的操作")
    @PutMapping("")
    public ResultData updateByPrimaryKeySelective(@Parameter(description = "修改文件") @RequestBody SysFile sysFile) {
        sysFileService.updateByPrimaryKeySelective(sysFile);
        return decide(Constants.SUCCESS_UPDATE);
    }


    @Operation(summary = "批量删除", description = "批量删除文件的操作")
    @DeleteMapping("")
    public ResultData delBatch(@Parameter(description = "数据ID集合数组，传body") @RequestBody Set<Long> ids) {
        return decide(String.format("已成功删除%d条数据", sysFileService.delBatch(ids)));
    }

    @Operation(summary = "文件删除", description = "删除文件的操作")
    @DeleteMapping("/path")
    public ResultData delBatch(@Parameter(description = "文件地址") @RequestParam String fileUrl) {
        sysFileService.delFile(fileUrl);
        return decide(Constants.SUCCESS_DEL);
    }

    @Operation(summary = "模糊分页", description = "模糊分页文件的操作")
    @PostMapping("/list")
    public ResultData list(@Parameter(description = "模糊分页文件") @RequestBody PageRequest<SysFile> request) {
        return decide(sysFileService.list(request));
    }


    @Operation(summary = "查询单条", description = "查询单条文件的操作")
    @GetMapping("")
    public ResultData selectByPrimaryKey(@Parameter(description = "数据ID") @RequestParam Long id) {
        return decide(sysFileService.selectByPrimaryKey(id));
    }

    @Operation(summary = "查询所有", description = "查询所有文件的操作")
    @GetMapping("/all")
    public ResultData all() {
        return decide(sysFileService.all());
    }


    @Operation(summary = "查询所有文件标签", description = "查询所有文件标签")
    @GetMapping("/flag")
    public ResultData allFlag(@Parameter(description = "文件类型") @RequestParam(required = false) String type) {
        return decide(sysFileService.allFlag(type));
    }
}
